package bom.service.impl.organization;

import bom.configuration.constant.SystemStaticConst;
import bom.configuration.util.JsonHelper;
import bom.configuration.util.ListUtil;
import bom.configuration.util.PrivilegeUtil;
import bom.configuration.util.UserInfo;
import bom.dao.organization.RoleAssociateTreeDao;
import bom.dao.organization.RoleWriteAssociateTreeDao;
import bom.dao.organization.UserRoleDao;
import bom.mapper.TreeMapper;
import bom.pojo.organization.*;
import bom.service.i.organization.TreeService;
import bom.service.i.organization.UserRoleService;
import bom.service.i.organization.UserService;
import com.github.pagehelper.util.StringUtil;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Fancyears·Maylos·Malvis
 * @Description:
 * @Date: Created in  2018/11/27 15:20
 * @Modified By:
 */
@Service
@Transactional(rollbackFor = {IllegalArgumentException.class})
@EnableTransactionManagement(proxyTargetClass = true)
public class UserRoleServiceImpl implements UserRoleService {
    @Autowired(required = false)
    private UserRoleDao userRoleDao;
    @Autowired(required = false)
    private RoleAssociateTreeDao roleAssociateTreeDao;
    @Autowired(required = false)
    private RoleWriteAssociateTreeDao roleWriteAssociateTreeDao;
    @Autowired
    UserService userService;
    @Autowired
    TreeService treeService;
    @Autowired
    TreeMapper treeMapper;

    /**
     * 功能描述：获取权限菜单数据
     *
     * @param entity
     * @return
     */
    public UserRole getUserRoleAssociate(UserRole entity) {
        return userRoleDao.getUserRoleAssociate(entity);
    }


    /**
     * 功能描述：获取用户写权限菜单数据
     *
     * @param entity
     * @return
     */
    public UserRole getUserWriteRoleAssociate(UserRole entity) {
        return userRoleDao.getUserWriteRoleAssociate(entity);
    }

    /**
     * 查询当前角色权限的引用关系
     *
     * @param id 角色id
     * @return
     */
    public Integer getUserRoleReferenceCount(Long id) {
        return userRoleDao.getUserRoleReferenceCount(id);
    }

    /**
     * 功能描述：删除角色数据
     *
     * @param entityList
     * @return
     * @throws Exception
     */
    @Override
    public boolean removeBath(List<UserRole> entityList) throws Exception {
        for (UserRole userRole : entityList) {
            roleAssociateTreeDao.removeTreeByRoleId(userRole);
        }
        return userRoleDao.removeBath(entityList) > 0 ? true : false;
    }

    /**
     * 增加角色数据
     *
     * @param entity 保存对象
     * @return
     * @throws Exception
     */
    @Override
    public boolean save(UserRole entity) throws Exception {
        entity.packagingTrees(entity.getTreeArray());
        List<Tree> treeList = entity.getTreeList();
        boolean success = userRoleDao.save(entity)>0?true:false;
        for (Tree tree : treeList) {
            roleAssociateTreeDao.save(new RoleAssociateTree(entity.getId(), tree.getId()));
        }
        return success;
    }

    @Override
    public boolean update(UserRole entity) throws Exception {
        entity.packagingTrees(entity.getTreeArray());
        List<Tree> treeList = entity.getTreeList();
        roleAssociateTreeDao.removeTreeByRoleId(entity);
        for (Tree tree : treeList) {
            roleAssociateTreeDao.save(new RoleAssociateTree(entity.getId(), tree.getId()));
        }
        return userRoleDao.update(entity)>0?true:false;
    }

    /**
     * 保存设定的用户权限信息
     *
     * @param userRole
     * @return
     */
    public boolean saveRoleWritePrivilege(UserRole userRole) {
        try {
            userRole.packagingTrees(userRole.getTreeArray());
            List<String> list = Lists.newArrayList(userRole.getTreeArray().split(","));
            roleWriteAssociateTreeDao.removeTreeByRoleId(userRole);
            for (String s : list) {
                roleWriteAssociateTreeDao.save(new RoleWriteAssociateTree(userRole.getId(), Long.valueOf(s)));
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Map<String, Object> loadRoles() {
        Map<String, Object> result = new HashMap<String, Object>();
        List<UserRole> userRoleList = query(null);
        result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
        result.put("list", userRoleList);
        return result;
    }

    private List<UserRole> query(Object o) {
        return null;
    }

    @Override
    public Map<String, Object> update(User entity) throws Exception {
        User user = userService.findByLogin(entity.getLogin());//编辑的用户
        if (null != user) {
            List<UserRole> userRoles = user.getRoles();//系统已存在的用户角色
            User loginUser = userService.findByLogin(UserInfo.getUser().getLogin());//当前登录用户
            if (!loginUser.getLogin().equals(user.getLogin())) {
                if (!PrivilegeUtil.hasAdministratorPrivilege(loginUser)) {
                    Map<String, Object> map = new HashMap<>();
                    map.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
                    map.put(SystemStaticConst.MSG, "不具备系统管理员权限的用户不能编辑其他员工信息！");
                    return map;
                } else {//A系统管理员 修改  B系统管理员权限
                    if (!SystemStaticConst.DCPROXY.equals(loginUser.getLogin())) {
                        for (UserRole role : userRoles) {
                            if (PrivilegeUtil.ROLE_ADMIN.equals(role.getName())) {
                                String id = String.valueOf(role.getId());
                                if (null != entity.getRoleArray()) {
                                    List<String> list = Lists.newArrayList(entity.getRoleArray().split(","));
                                    if (!list.contains(id)) {
                                        Map<String, Object> map = new HashMap<>();
                                        map.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
                                        map.put(SystemStaticConst.MSG, "只有dcproxy账户才能移除其他用户的系统管理员权限！");
                                        return map;
                                    }
                                } else {
                                    Map<String, Object> map = new HashMap<>();
                                    map.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
                                    map.put(SystemStaticConst.MSG, "只有dcproxy账户才能移除其他用户的系统管理员权限！");
                                    return map;
                                }
                            }
                        }
                    }
                }
            }

            if (SystemStaticConst.DCPROXY.equals(entity.getLogin())) {
                for (UserRole role : userRoles) {
                    if (PrivilegeUtil.ROLE_ADMIN.equals(role.getName())) {
                        if (StringUtil.isEmpty(entity.getRoleArray()) || !entity.getRoleArray().contains(String.valueOf(role.getId()))) {
                            Map<String, Object> map = new HashMap<>();
                            map.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
                            map.put(SystemStaticConst.MSG, "dcproxy的系统管理员权限不能删除！");
                            return map;
                        }
                    }
                }
            }
            String ids = entity.getRoleArray();
            boolean write = true;
            if (!PrivilegeUtil.administrator()) {
                if (StringUtil.isEmpty(ids) && ListUtil.isEmpty(userRoles)) {
                    write = true;
                } else if (StringUtil.isEmpty(ids) && ListUtil.isNotEmpty(userRoles)) {
                    write = false;
                } else if (!StringUtil.isEmpty(ids) && ListUtil.isEmpty(userRoles)) {
                    write = false;
                } else if (ListUtil.isNotEmpty(userRoles) && !StringUtil.isEmpty(ids)) {
                    List<String> list = Lists.newArrayList(ids.split(","));
                    if (list.size() != userRoles.size()) {
                        write = false;
                    } else {
                        for (String s : list) {
                            boolean find = false;
                            for (UserRole role : userRoles) {
                                if (s.equals(String.valueOf(role.getId()))) {
                                    find = true;
                                    break;
                                }
                            }
                            if (!find) {
                                write = false;
                                break;
                            }
                        }
                    }

                }
                if (!write) {
                    Map<String, Object> map = new HashMap<>();
                    map.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
                    map.put(SystemStaticConst.MSG, "只有系统管理员权限账户才能修改员工所属权限信息！");
                    return map;
                }
            }
        }
        boolean success = userService.update(entity);
        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
            result.put(SystemStaticConst.MSG, "更新数据成功！");
        } else {
            result.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
            result.put(SystemStaticConst.MSG, "更新数据失败！");
        }
        return result;
    }

    @Override
    public Map<String, Object> loadRoleTree(UserRole entity) {
        entity = getUserRoleAssociate(entity);
        List<Tree> treeList = treeService.query(null);
        if (entity != null) {
            for (Tree tree : entity.getTreeList()) {
                treeList.stream().forEach(t -> {
                    if (t.getId() == tree.getId()) {
                        t.setChecked(true);
                    }
                });
            }
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
        result.put("data", treeMapper.treesToTressDTOs(treeList));
        return result;
    }

    @Override
    public Map<String, Object> loadRoleWriteTree(UserRole entity) {
        entity = getUserWriteRoleAssociate(entity);
        List<Tree> treeList = treeService.query(null);
        if (entity != null) {
            for (Tree tree : entity.getTreeList()) {
                treeList.stream().forEach(t -> {
                    if (t.getId() == tree.getId()) {
                        t.setChecked(true);
                    }
                });
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
        result.put("data", treeMapper.treesToTressDTOs(treeList));
        return result;
    }

    @Override
    public Map<String, Object> removeByBatch(String json) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        com.alibaba.fastjson.JSONArray array = com.alibaba.fastjson.JSONObject.parseArray(json);
        String id = "";
        for (int i = 0; i < array.size(); i++) {
            com.alibaba.fastjson.JSONObject object = array.getJSONObject(i);
            if (object.containsKey("id")) {
                id = object.getString("id");
                break;
            }
        }
        if (StringUtil.isEmpty(id)) {
            result.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
            result.put(SystemStaticConst.MSG, "非法参数！");
            return result;
        }

        Integer count = getUserRoleReferenceCount(Long.valueOf(id));
        if (count != null && count > 0) {
            result.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
            result.put(SystemStaticConst.MSG, "当前要删除的权限信息正在被用户所引用,无法删除！");
            return result;
        }
        removeBath((List<UserRole>) JsonHelper.toList(json, (Class<UserRole>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]));
        result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
        result.put(SystemStaticConst.MSG, "删除数据成功！");
        return result;
    }

    @Override
    public UserRole get(UserRole entity) {
        return null;
    }

    @Override
    public Map<String, Object> updateRole(UserRole entity) throws Exception {
        boolean success = update(entity);
        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
            result.put(SystemStaticConst.MSG, "操作成功！");
        } else {
            result.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
            result.put(SystemStaticConst.MSG, "操作失败，请稍后重试！");
        }
        return result;
    }

    @Override
    public Map<String, Object> saveWritePrivilege(UserRole entity) {
        User user = UserInfo.getUser();
        Map<String, Object> result = new HashMap<>();
        if (!PrivilegeUtil.hasAdministratorPrivilege(user)) {
            result.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
            result.put(SystemStaticConst.MSG, "不具备系统管理员权限的用户不能进行此操作！");
        }
        boolean success = saveRoleWritePrivilege(entity);
        if (success) {
            result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
            result.put(SystemStaticConst.MSG, "操作成功！");
        } else {
            result.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
            result.put(SystemStaticConst.MSG, "操作失败,请稍后重试！");
        }
        return result;
    }
}